package com.zxy.express.handler;

import com.autopai.base.common.web.HttpContextUtils;
import com.autopai.base.common.web.constant.Constant;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 公共字段，自动填充值
 *
 * @author yangyong
 */
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {
    private final static String CREATED_TIME = "updateTime";
    private final static String UPDATE_TIME = "createTime";
    private final static String OPER_USER_ID = "operUserId";

    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = getUserId();
        Date date = new Date();
        strictInsertFill(metaObject, CREATED_TIME, Date.class, date);
        strictInsertFill(metaObject, CREATED_TIME, Date.class, date);
        if (userId == null) {
            strictInsertFill(metaObject, OPER_USER_ID, String.class, "");
            return;
        }
        if (StringUtils.isEmpty(userId)) {
            strictInsertFill(metaObject, OPER_USER_ID, String.class, "");
            return;
        }
        // 创建者
        strictInsertFill(metaObject, OPER_USER_ID, String.class,userId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
        String userId = getUserId();
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        // 更新者
        strictInsertFill(metaObject, OPER_USER_ID, String.class, userId);
    }

    private String getUserId() {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (request != null) {
            String userId = request.getHeader(Constant.USER_KEY);
            return userId;
        }
        return null;
    }
}